package com.yylending.las.repay.repaydetail;

import android.text.TextUtils;

import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * Created by ying_he on 2017/6/9.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class RepayDetailListPresenter extends Presenter<RepayDetailListModel, RepayDetailListPresenter.View> {
	private static final String TAG = RepayDetailListPresenter.class.getSimpleName();
	public static final String TYPE_NO_ID_CARD = "-1";
	public static final String TYPE_SINGLE_REPAY_DETAIL = "1";
	public static final String TYPE_MULTI_REPAY_DETAIL = "2";
	// 后台找不到身份证信息
	private static final String CODE_NO_ID_CARD = "100010";
	// 没有借款
	private static final String CODE_NO_REPAY_INFO = "-1";

	private RepayDetailListPresenter.View mView;

	public static class Generator implements PresenterFactory<RepayDetailListPresenter> {
		@Override
		public RepayDetailListPresenter create() {
			return new RepayDetailListPresenter();
		}
	}

	@Override
	public void attach(RepayDetailListPresenter.View view) {
		mView = view;
		mModel = new RepayDetailListModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		void getRepayDetailSuccess(String type, ArrayList<RepayDetailListModel.Repay.RepayDetail> detail);

		void obtainRepayListFailed(String tips);
	}

	public void getRepayDetailList(String loanNo, String type) {
		RepayDetailListModel.RequestParams requestParams = new RepayDetailListModel.RequestParams();
		requestParams.loanNo = loanNo;
		requestParams.type = type;
		execute(requestParams, FUNCTIONAL_CODE, true);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getRepayDetailListResult(RepayDetailListModel.RepayListResult result) {
		ArrayList<RepayDetailListModel.Repay.RepayDetail> repayDetails = new ArrayList<>();
		if (BaseResultEntity.isResponseSuccess(result)) {
			if (result.getData() != null && !TextUtils.equals(CODE_NO_REPAY_INFO, result.getData().repayStatus) && result.getData().detail != null) {
				repayDetails.addAll(result.getData().detail);
			}

			if (TextUtils.equals(TYPE_SINGLE_REPAY_DETAIL, result.getData().type)) {
				mView.getRepayDetailSuccess(TYPE_SINGLE_REPAY_DETAIL, repayDetails);
			} else {
				mView.getRepayDetailSuccess(TYPE_MULTI_REPAY_DETAIL, repayDetails);
			}
		} else if (TextUtils.equals(CODE_NO_ID_CARD, result.getRetCode())) {
			mView.getRepayDetailSuccess(TYPE_NO_ID_CARD, repayDetails);
		} else {
			mView.obtainRepayListFailed(result.getRetMsg());
		}
	}
}

